package com.sky.common.http;



import com.sky.common.http.exception.HttpResponseException;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * http响应内容封装
 */
public class HttpDecorateResponse {

    private int code;
    private HttpEntity httpEntity;

    public HttpDecorateResponse() {
    }

    public static HttpDecorateResponse build(org.apache.http.HttpResponse response) {
        HttpDecorateResponse basicHttpResponse = new HttpDecorateResponse();
        basicHttpResponse.code = response.getStatusLine().getStatusCode();
        basicHttpResponse.httpEntity = response.getEntity();
        return basicHttpResponse;
    }

    public int getCode() {
        return this.code;
    }

    public Result result() {
        return new Result(this.httpEntity);
    }

    public static class Result {
        private final HttpEntity httpEntity;

        public Result(HttpEntity httpEntity) {
            this.httpEntity = httpEntity;
        }

        public String string() {
            return string("UTF-8");
        }

        public String string(String  charset) {
            try {
                return EntityUtils.toString(this.httpEntity, Charset.forName(charset));
            } catch (IOException var2) {
                throw new HttpResponseException(var2);
            }
        }

        public byte[] bytes() {
            try {
                return EntityUtils.toByteArray(this.httpEntity);
            } catch (IOException var2) {
                throw new HttpResponseException(var2);
            }
        }
    }
}
